package com.cjack.frenchexcel.controller;

import com.cjack.frenchexcel.config.AjaxResult;
import com.cjack.frenchexcel.enumInfo.DataDefineTypeEnum;
import com.cjack.frenchexcel.exception.CommonException;
import com.cjack.frenchexcel.model.DataDefineModel;
import com.cjack.frenchexcel.service.DataDefineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 一些公用的key-value数据项管理
 * Created by root on 4/21/19.
 */
@RestController
@RequestMapping("/dataDefine")
public class DataDefineEndpoint extends BaseEndpoint{

    @Autowired
    DataDefineService service;

    /**
     * 列表
     * @return
     */
    @RequestMapping(value = "/list/{type}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult list( @PathVariable("type")String type) {
        //注意pageDate里面的页数是从0开始计算的
        List< DataDefineModel> datas = service.list( DataDefineTypeEnum.valueOf( type));
        return AjaxResult.SUCCESS( datas);
    }

    /**
     * 新增
     * @return
     */
    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addOrUpdate( DataDefineModel model) {
        try{
            if( isAdd( model.getId())){
                model.setCreateTime( new Date());
            }
            model.setUpdateTime( new Date());
            service.add( model);
            return AjaxResult.SUCCESS();
        }catch ( CommonException e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult del( @RequestParam("ids") String ids) {
        try{
            service.del( ids);
            return AjaxResult.SUCCESS( "删除成功");
        }catch ( Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }
}
